package com.aiyige.richtexteditor.util;

import android.text.TextUtils;

import com.aiyige.base.db.dao.UploadFileDao;
import com.aiyige.base.db.table.UploadFile;
import com.aiyige.model.moment.entity.PersistentMapping;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.richtexteditor.model.Persistent;
import com.aiyige.richtexteditor.model.RTELocalMedia;
import com.aiyige.richtexteditor.model.RTEModel;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.ListUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.j256.ormlite.stmt.QueryBuilder;
import com.vondear.rxtools.RxFileTool;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.LinkedList;
import java.util.List;


public class RichTextUtil {

    public static final String TAG = RichTextUtil.class.getSimpleName();

    public static List<PersistentMapping> convertToPersistentMappingList(List<Persistent> persistentList) {
        List<PersistentMapping> persistentMappingList = new LinkedList<>();
        if (ListUtil.isEmpty(persistentList)) return persistentMappingList;
        for (Persistent persistent : persistentList) {
            persistentMappingList.add(PersistentMapping.newBuilder()
                    .persistentId(persistent.getPersistentId())
                    .url(persistent.getUrl())
                    .build());
        }
        return persistentMappingList;
    }

    public static String handleRichText(String photoDomain, String videoDomain, RTEModel rteModel, List<Persistent> persistentList) {
        if (rteModel == null) return "";
        if (TextUtils.isEmpty(rteModel.getContent())) return "";
        if (ListUtil.isEmpty(rteModel.getRteLocalMediaList())) return rteModel.getContent();
        try {
            Document doc = Jsoup.parseBodyFragment(rteModel.getContent());
            for (RTELocalMedia rteLocalMedia : rteModel.getRteLocalMediaList()) {
                try {
                    Element element = doc.getElementById(rteLocalMedia.getMediaId());
                    if (element == null) continue;
                    List<UploadFile> uploadFileList;
                    try {
                        uploadFileList = UploadFileDao.getDao()
                                .queryBuilder()
                                .where()
                                .like(UploadFile.STORE_KEY_FIELD, "%" + rteLocalMedia.getMediaId() + "%")
                                .and()
                                .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                                .query();
                    } catch (Exception e) {
                        uploadFileList = new LinkedList<>();
                    }
                    UploadFile uploadFile = ListUtil.getFirstItem(uploadFileList);
                    if (uploadFile != null) {
                        switch (uploadFile.getFileType()) {
                            case PublishUtil.UPLOAD_FILE_TYPE_PHOTO:
                                element.attr("id", "");
                                element.attr("src", photoDomain + uploadFile.getStoreKey());
                                break;
                            case PublishUtil.UPLOAD_FILE_TYPE_VIDEO:
                                element.attr("id", "");
                                element.attr("src", videoDomain + uploadFile.getStoreKey());
                                element.attr("poster", photoDomain + uploadFile.getCoverStoreKey());
                                if (persistentList != null) {
                                    persistentList.add(Persistent.newBuilder()
                                            .persistentId(uploadFile.getPersistentId())
                                            .url(videoDomain + uploadFile.getStoreKey())
                                            .build());
                                }
                                break;
                        }
                    } else {
                        if (element.hasAttr("id")) {
                            element.attr("id", "");
                        }
                        if (element.hasAttr("src")) {
                            element.attr("src", "");
                        }
                        if (element.hasAttr("poster")) {
                            element.attr("poster", "");
                        }
                    }
                } catch (Exception e) {

                }
            }
            return doc.body().html();
        } catch (Exception e) {
            return rteModel.getContent();
        }
    }


    public static String handleRichTextContent(String photoDomain, String videoDomain, String content) {
        try {
            JSONObject delta = JSON.parseObject(content);
            JSONArray ops = delta.getJSONArray("ops");
            if (ops == null || ops.isEmpty()) return content;
            int opsSize = ops.size();
            for (int i = 0; i < opsSize; ++i) {
                try {
                    JSONObject op = ops.getJSONObject(i);
                    JSONObject insert = op.getJSONObject("insert");
                    if (insert.containsKey("image")) {
                        JSONObject image = insert.getJSONObject("image");
                        String id = image.getString("id");
                        if (TextUtils.isEmpty(id)) continue;
                        List<UploadFile> uploadFileList;
                        try {
                            QueryBuilder<UploadFile, Integer> queryBuilder = UploadFileDao.getDao().queryBuilder();
                            queryBuilder.where()
                                    .like(UploadFile.STORE_KEY_FIELD, "%" + id + "%")
                                    .and()
                                    .eq(UploadFile.FILE_TYPE_FIELD, PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                            uploadFileList = queryBuilder.query();
                        } catch (Exception e) {
                            uploadFileList = new LinkedList<>();
                        }
                        if (ListUtil.isEmpty(uploadFileList)) {
                            image.put("id", "");
                            image.put("path", "");
                        } else {
                            UploadFile uploadFile = uploadFileList.get(0);
                            image.put("id", "");
                            image.put("path", photoDomain + uploadFile.getStoreKey());
                        }
                    } else if (insert.containsKey("video")) {
                        JSONObject video = insert.getJSONObject("video");
                        String id = video.getString("id");
                        if (TextUtils.isEmpty(id)) continue;
                        List<UploadFile> uploadFileList;
                        try {
                            QueryBuilder<UploadFile, Integer> queryBuilder = UploadFileDao.getDao().queryBuilder();
                            queryBuilder.where()
                                    .like(UploadFile.STORE_KEY_FIELD, "%" + id + "%")
                                    .and()
                                    .eq(UploadFile.FILE_TYPE_FIELD, PublishUtil.UPLOAD_FILE_TYPE_VIDEO)
                                    .and()
                                    .ne(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                            uploadFileList = queryBuilder.query();
                        } catch (Exception e) {
                            uploadFileList = new LinkedList<>();
                        }
                        if (ListUtil.isEmpty(uploadFileList)) {
                            video.put("id", "");
                            video.put("path", "");
                            video.put("poster", "");
                            video.put("persistentId", "");
                        } else {
                            UploadFile uploadFile = uploadFileList.get(0);
                            video.put("id", "");
                            video.put("path", videoDomain + uploadFile.getStoreKey());
                            video.put("poster", photoDomain + uploadFile.getCoverStoreKey());
                            video.put("persistentId", uploadFile.getPersistentId());
                        }
                    }
                } catch (Exception e) {
                }
            }
            return JSON.toJSONString(delta);
        } catch (Exception e) {
            return content;
        }
    }

    public static List<RTELocalMedia> alignRTELocalMediaList(List<RTELocalMedia> rteLocalMediaList, List<String> mediaIdList) {
        List<RTELocalMedia> alignedList = new LinkedList<>();
        if (ListUtil.isEmpty(rteLocalMediaList)) return alignedList;
        if (ListUtil.isEmpty(mediaIdList)) return alignedList;
        for (RTELocalMedia rteLocalMedia : rteLocalMediaList) {
            try {
                if (mediaIdList.contains(rteLocalMedia.getMediaId())) {
                    alignedList.add(rteLocalMedia);
                }
            } catch (Exception e) {

            }
        }
        return alignedList;
    }

    public static List<RTELocalMedia> alignRTELocalMediaListToHtml(List<RTELocalMedia> rteLocalMediaList, String html) {
        List<RTELocalMedia> alignedList = new LinkedList<>();
        if (ListUtil.isEmpty(rteLocalMediaList)) return alignedList;
        try {

            Document doc = Jsoup.parseBodyFragment(html);
            for (RTELocalMedia rteLocalMedia : rteLocalMediaList) {
                try {
                    Element element = doc.getElementById(rteLocalMedia.getMediaId());
                    if (element != null) {
                        alignedList.add(rteLocalMedia);
                    }
                } catch (Exception e) {

                }
            }
        } catch (Exception e) {
        }
        return alignedList;
    }

    public static boolean isLocalUrl(String url) {
        return isLocalUrl(url, true);
    }

    public static boolean isLocalUrl(String url, boolean checkExist) {
        if (checkExist) {
            return !TextUtils.isEmpty(url) && url.toLowerCase().startsWith("file") && RxFileTool.fileExists(extractStandardLocalPath(url));
        } else {
            return !TextUtils.isEmpty(url) && !url.toLowerCase().startsWith("file");
        }
    }

    public static String extractStandardLocalPath(String localUrl) {
        if (TextUtils.isEmpty(localUrl)) return "";
        if (localUrl.toLowerCase().startsWith("file://")) {
            return localUrl.substring(7);
        } else {
            return localUrl;
        }
    }


    public static void uploadRTELocalMedia(int parentType, String parentId, List<RTELocalMedia> rteLocalMediaList) throws Exception {
        for (RTELocalMedia item : rteLocalMediaList) {
            switch (item.getType()) {
                case RTELocalMedia.TYPE_PHOTO: {
                    UploadFile photo = UploadFile.newBuilder()
                            .userId(AccountUtil.getCurrentUser().getId())
                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                            .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                            .fileLocalUrl(item.getPhotoUrl())
                            .storeKey(PublishUtil.generatePhotoFileStoreKey(item.getMediaId(), item.getPhotoUrl()))
                            .description("")
                            .parentId(parentId)
                            .parentType(parentType)
                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                            .totalSize(FileUtil.getFileSize(item.getPhotoUrl()))
                            .build();
                    UploadFileDao.getDao().create(photo);
                    break;
                }
                case RTELocalMedia.TYPE_VIDEO: {
                    UploadFile videoCover = UploadFile.newBuilder()
                            .userId(AccountUtil.getCurrentUser().getId())
                            .fileLocalUrl(item.getVideoOriginalCoverUrl())
                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                            .storeKey(PublishUtil.generatePhotoFileStoreKey(item.getVideoOriginalCoverUrl()))
                            .parentId(parentId)
                            .parentType(parentType)
                            .totalSize(FileUtil.getFileSize(item.getVideoOriginalCoverUrl()))
                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                            .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                            .build();
                    UploadFileDao.getDao().create(videoCover);
                    UploadFile video = UploadFile.newBuilder()
                            .userId(AccountUtil.getCurrentUser().getId())
                            .fileLocalUrl(item.getVideoUrl())
                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_VIDEO)
                            .storeKey(PublishUtil.generateVideoFileStoreKey(item.getMediaId(), item.getVideoUrl()))
                            .parentId(parentId)
                            .parentType(parentType)
                            .totalSize(FileUtil.getFileSize(item.getVideoUrl()))
                            .duration(item.getMediaDuration())
                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                            .progressStatus(PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE)
                            .coverStoreKey(videoCover.getStoreKey())
                            .coverUrl(videoCover.getFileLocalUrl())
                            .build();
                    UploadFileDao.getDao().create(video);
                    break;
                }
            }
        }
    }

}
